package com.party.jackclientandroid;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.api.UserService;
import com.party.jackclientandroid.base.MyException;
import com.party.jackclientandroid.bean.AppInfo;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.bean.RegisterInfo;
import com.party.jackclientandroid.bean.VerCode;
import com.party.jackclientandroid.bean.User;
import com.party.jackclientandroid.controller.DialogController;
import com.party.jackclientandroid.controller.VerCodeTimer;
import com.party.jackclientandroid.event.AuthResultEvent;
import com.party.jackclientandroid.utils.CheckUtils;
import com.party.jackclientandroid.utils.ConstUtils;
import com.party.jackclientandroid.wxapi.WXPayUtils;
import com.uuzuche.lib_zxing.activity.CodeUtils;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class RegisterActivity extends BaseActivityTitle {

    @BindView(R.id.invite_phone_et)
    EditText invite_phone_et;
    @BindView(R.id.phone_et)
    EditText phone_et;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.getVerCodeBtn)
    Button getVerCodeBtn;

    UserService userService;
    VerCodeTimer mVerCodeTimer;
    String phone;
    AppInfo mAppInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initData();
        EventBus.getDefault().register(this);
    }

    protected void initData() {
        setMiddleText("立即注册");
        mAppInfo = (AppInfo) getIntent().getSerializableExtra("appInfo");
        userService = new UserService(this);
        if (mAppInfo == null) {
            getAppId();
        } else {
            getWxCode(mAppInfo);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 获取一键登录信息。
     */
    private void getAppId() {
        showLoadingDialog();
        addDisposableIoMain(userService.getAppId(), new DefaultConsumer<AppInfo>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<AppInfo> baseBean) {
                mAppInfo = baseBean.getData();
                getWxCode(mAppInfo);
                hideAlertDialog();
            }
        });
    }

    public void getWxCode(AppInfo appInfo) {
        try {
            WXPayUtils build = new WXPayUtils.WXPayBuilder().build();
            build.getUserCode(mActivity, appInfo.getWxAppId());
        } catch (MyException e) {
            showToast(e.getMessage());
        }
    }

    /**
     * 微信授权成功,回调
     *
     * @param authResultEvent
     */
    @Subscribe(priority = 100)//011sh1Pi03TPAn1aStPi0SiFOi0sh1P9
    public void authFinish(AuthResultEvent authResultEvent) {
        EventBus.getDefault().cancelEventDelivery(authResultEvent);
        checkWxIsRegister(authResultEvent.getCode());
    }

    public void checkWxIsRegister(String code) {
        showLoadingDialog();
        addDisposableIoMain(userService.checkWxIsRegister(code), new DefaultConsumer<RegisterInfo>(mApplication) {
            @Override
            public void operateError(BaseResult<RegisterInfo> baseBean) {
                hideAlertDialog();
                DialogController.showMustConfirmDialog(mActivity, "温馨提示", "该微信已经绑定账户", (View v) -> {
                    finish();
                });
            }

            @Override
            public void operateSuccess(BaseResult<RegisterInfo> baseBean) {
                hideAlertDialog();
                mAppInfo.setRegisterKey(baseBean.getData().getRegisterKey());
            }
        });
    }


    /**
     * 获取验证码
     */
    @OnClick(R.id.getVerCodeBtn)
    public void clickGetVerCode() {
        phone = phone_et.getText().toString();
        if (phone.trim().length() != 11 || !phone.startsWith("1")) {
            showToast("号码格式有误");
            return;
        }
        addDisposableIoMain(userService.getRegisterVerCode(phone), new DefaultConsumer<VerCode>(mApplication) {
            @Override
            public void operateSuccess(BaseResult<VerCode> baseBean) {
                if ("phone".equals(baseBean.getData().getType())) {
                    DialogController.showMustConfirmDialog(mActivity,
                            "语音验证",
                            baseBean.getMessage(), (View v) -> {
                            });
                }
                mVerCodeTimer = new VerCodeTimer(userService.second, getVerCodeBtn);
                mVerCodeTimer.setChangeView(phone_et, getVerCodeBtn);
                mVerCodeTimer.start();
            }
        });
    }

    public void register() {
        String addressCode = mApplication.getMap().getAdCode();
        try {
            String verCode = CheckUtils.checkData(et_code, "请输入验证码");
            String phone = CheckUtils.checkData(phone_et, "请输入手机号");
            String inviteCode = CheckUtils.checkData(invite_phone_et, "没有输入推荐人");
            CheckUtils.checkData(addressCode == null, null, "没有获取到定位信息");

            if (mAppInfo.getRegisterKey() == null) {
                DialogController.showMustConfirmDialog(mActivity, "温馨提示", "需要绑定微信账号才能注册", (View v) -> {
                    getWxCode(mAppInfo);
                });
                return;
            }
            showLoadingDialog("正在注册...");
            addDisposableIoMain(userService.registerUser(mAppInfo.getRegisterKey(), phone, verCode, inviteCode, addressCode), new DefaultConsumer<User>(mApplication) {
                @Override
                public void operateError(String message) {
                    super.operateError(message);
                    hideAlertDialog();
                    showToast(message);
                }

                @Override
                public void operateSuccess(BaseResult<User> baseBean) {
                    hideAlertDialog();
                    User user = baseBean.getData();
                    if (user != null) {
                        mApplication.finishOtherActivity(RegisterActivity.this);
                        mApplication.setUser(user);
                        startActivity(MainActivity.class, "isRegister", "true");
                        finish();
                    } else {
                        showToast("注册失败");
                    }
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) throws Exception {
                    hideAlertDialog();
                    showToast(throwable.getMessage());
                }
            });

        } catch (Exception e) {
            showToast(e.getMessage());
        }
    }

    @OnClick({R.id.scan_code_iv, R.id.register_btn, R.id.login_tv})
    public void handleClickSth(View view) {
        switch (view.getId()) {
            case R.id.scan_code_iv:
//                Intent intent = new Intent(mActivity, ScanActivity.class);
//                startActivityForResult(intent, ConstUtils.SCAN_CODE);
                break;
            case R.id.register_btn:
                register();
                break;
            case R.id.login_tv:
                finish();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ConstUtils.SCAN_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    String resultStr = bundle.getString(CodeUtils.RESULT_STRING);
                    if (!TextUtils.isEmpty(resultStr)) {
                        String subStr = resultStr.substring(resultStr.indexOf('=') + 1);
                        invite_phone_et.setText(subStr);
                    }
                }
        }
    }
}
